package cn.message.web;

import cn.itcast.pojo.admin;
import cn.itcast.pojo.image;
import cn.itcast.pojo.permission;
import cn.itcast.pojo.role;
import cn.itcast.util.OutputStringController;
import cn.message.service.IPermissionService;
import cn.message.service.IRoleService;
import cn.web.web_module.util.IconPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 郭智超
 * @create 2020-05-18 15:35
 */
@Slf4j
@RestController
@RequestMapping(value="/dhn/message",produces="text/html;charset=UTF-8")
public class PermissionController {

    @Resource
    private IRoleService roleService;

    @Resource
    private OutputStringController osc;

    @Resource
    private cn.message.service.adminService adminService;

    @Resource
    private IPermissionService permissionService;

    @ResponseBody
    @RequestMapping("/getAllRole")
    public String getAllRole(@RequestBody Map<String,String> map){
        String results = "";
        Map<String, Object> resultMap = roleService.getAllRole(map);
        //获取所有的角色信息
        Object roleList = resultMap.get("roleList");
        //获取总记录数
        int count = (int) resultMap.get("count");

        if(roleList == null){
            results = osc.resultFailure("查询所有角色信息失败", "");
            log.debug("查询所有角色信息失败");
        }
        else {
            results = osc.resultSuccess("查询所有角色信息成功",roleList, count);
            log.debug("查询所有角色信息成功");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/deleteRole")
    public String deleteRole(@RequestBody Map<String,String> map){
        String results = "";
        int roleId = Integer.parseInt(map.get("roleId"));
        Boolean aBoolean = roleService.deleteRole(roleId);
        if(aBoolean){
            results = osc.success("删除成功");
        }else {
            results = osc.failure("删除失败");
        }
        return results;
    }

    /**
     * 获取所有的权限名和权限id
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/getPermissions")
    public String getPermissions(){
        String results = "";
        List<permission> permissionList = permissionService.getPermissions();

        if(permissionList == null){
            results = osc.resultFailure("查询所有权限名称和权限id信息失败", "");
        }
        else {
            results = osc.resultSuccess("查询所有权限名称和权限id信息成功",permissionList);
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/addRole")
    public String addRole(@RequestBody Map<String,String> map){
        String results = "";
        if(map.get("roleName").isEmpty()){
            return osc.failure("角色名不能为空");
        }
        //判断输入的角色名是否已经存在
        Boolean isExist = roleService.getRoleByRoleName(map.get("roleName"));
        if(isExist == false){
            return osc.failure("该角色名已存在");
        }

        //判断是否给该角色添加了权限
        if(map.get("permissionIds").isEmpty()){
            return osc.failure("您还没有给该角色添加权限");
        }

        Boolean aBoolean = roleService.addRole(map);
        if(aBoolean){
            results = osc.success("增加成功");
        }else {
            results = osc.failure("增加失败");
        }


        return results;
    }

    @ResponseBody
    @RequestMapping("/updateRole")
    public String updateRole(@RequestBody Map<String,String> map){
        String results = "";
        if(map.get("roleName").isEmpty()){
            return osc.failure("角色名不能为空");
        }

        //判断是否给该角色添加了权限
        if(map.get("permissionIds").isEmpty()){
            return osc.failure("您还没有给该角色添加权限");
        }

        Boolean aBoolean = roleService.updateRole(map);
        if(aBoolean){
            results = osc.success("修改成功");
        }else {
            results = osc.failure("修改失败");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/getAllAdmin")
    public String getAllAdmin(@RequestBody Map<String,String> map){
        String results = "";
        Map<String, Object> resultMap = adminService.getAllAdmin(map);
        //获取所有的管理员信息
        Object adminList = resultMap.get("adminList");
        //获取总记录数
        int count = (int) resultMap.get("count");

        if(adminList == null){
            results = osc.resultFailure("查询所有管理员信息失败", "");
        }
        else {
            results = osc.resultSuccess("查询所有管理员信息成功",adminList, count);
        }
        return results;
    }

    /**
     * 获取所有的角色名和角色id
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping("/getRoles")
    public String getRoles(){
        String results = "";
        List<role> roleList = roleService.getRoles();

        if(roleList == null){
            results = osc.resultFailure("查询所有角色信息失败", "");
        }
        else {
            results = osc.resultSuccess("查询所有角色信息成功",roleList);
        }
        return results;
    }

    @ResponseBody
    @PostMapping(value = "/addAdmin",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String addAdmin(HttpServletRequest request,
                           @RequestParam(value = "adminName",required = false) String adminName,
                           @RequestParam(value = "adminNickname",required = false) String adminNickname,
                           @RequestParam(value = "adminPhone",required = false) String adminPhone,
                           @RequestParam(value = "adminAddress",required = false) String adminAddress,
                           @RequestParam(value = "adminPassword",required = false) String adminPassword,
                           @RequestParam(value = "adminHeader",required = false) MultipartFile adminHeader,
                           @RequestParam(value = "roleIds",required = false) int[] roleIds){
        String results = "";
        if(adminName.isEmpty()){
            return osc.failure("管理员姓名不能为空");
        }
        if(adminNickname.isEmpty()){
            return osc.failure("管理员登录用户名不能为空");
        }
        if(adminPhone.isEmpty()){
            return osc.failure("管理员手机号不能为空");
        }
        if(roleIds == null){
            return osc.failure("请至少选择一个角色");
        }
        if(adminPassword.isEmpty()){
            return osc.failure("密码不能为空");
        }
        if(adminHeader == null){
            return osc.failure("管理员头像不能为空");
        }

        //判断输入的用户名是否已经存在
        Boolean orNotAdminNickName = adminService.isOrNotAdminNickName(adminNickname);
        if(orNotAdminNickName){
            return osc.failure("用户名已存在");
        }

        //设置文件存储路径
//        String iconPathEnum = "/usr/tomcat/images/dhn/icon/adminHeader/";

//        String iconPath = "/usr/tomcat/images/dhn/icon/adminHeader/";//松注释

        String iconPath = IconPath.ICONPATH +"icon/adminHeader/";//松注释
//        String iconPathEnum = "E:/job/testIconPath";
        FileOutputStream fos = null;
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = adminHeader.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            adminHeader.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }
        admin admin = new admin();
//        admin.setAdminHeader("http://120.79.51.10:8181/dhn/icon/adminHeader/"+iconName);
        admin.setAdminHeader("https://www.dhnep.cn:8181/dhn/icon/adminHeader/"+iconName);
//        admin.setAdminHeader("E:/job/testIconPath"+iconName);
        admin.setAdminAddress(adminAddress);
        admin.setAdminName(adminName);
        admin.setAdminNickname(adminNickname);
        admin.setAdminPhone(adminPhone);
        admin.setAdminPassword(adminPassword);
        admin.setCreateTime(new Date());
        admin.setAdminState(1);
        Boolean aBoolean = adminService.addAdminAndRole(admin,roleIds);
        if (!aBoolean) {
            results = osc.failure("添加管理员失败");
        } else {
            results = osc.success("添加管理员成功");
        }
        return results;
    }


    @ResponseBody
    @PostMapping(value = "/uploadAdminHeader",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String uploadPicture(HttpServletRequest request,
                                @RequestParam(value = "adminHeader",required = false) MultipartFile adminHeader,
                                @RequestParam(value = "adminId",required = false) Integer adminId){
        System.out.println("开始上传图片了-----------------------------------------------------------");
        String results="";
        if(adminHeader.isEmpty()){
            return osc.failure("图片为空，请上传图片");
        }
        if(adminId == null || adminId.equals("")){
            return osc.failure("id为空");
        }
        //设置文件存储路径
//        String iconPath = "/usr/tomcat/images/dhn/icon/adminHeader/";//松注释
        String iconPath = IconPath.ICONPATH+"icon/adminHeader/";//松注释

//        String iconPathEnum = "E:/job/testIconPath/";
        File files = new File(iconPath);
        if(!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录："+files);
            //如果目录不存在则创建目录
            files.mkdir();
        }
        //获取原始文件名称（包含格式）
        String originalIconName = adminHeader.getOriginalFilename();
        System.out.println("原始图片名称："+originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".")+1);
        System.out.println("图片类型："+iconType);

        //获取文件名称（不含格式）
        String iconName = originalIconName.substring(0,originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        //设置新文件名称（包含格式）
        iconName = newDate+iconName+"."+iconType;
        System.out.println("新文件名称"+iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPath,iconName);

        //将图片保存到指定位置
        try {
            adminHeader.transferTo(targetFile);
            System.out.println("上传成功");
        } catch (IOException e) {
            System.out.println("上传失败");
            e.printStackTrace();
            return osc.failure("上传图片失败");
        }

        admin admin = new admin();
        admin.setAdminId(adminId);
//        admin.setAdminHeader("http://120.79.51.10:8181/dhn/icon/adminHeader/"+iconName);
        admin.setAdminHeader("https://www.dhnep.cn:8181/dhn/icon/adminHeader/"+iconName);
//        admin.setAdminHeader("E:/job/testIconPath"+iconName);
        Boolean aBoolean = adminService.updateAdmin(admin);
        if (!aBoolean) {
            results = osc.failure("头像上传失败");
        } else {
            results = osc.success("头像上传成功");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/updateAdmin")
    public String updateAdmin(@RequestBody Map<String,String> map){
        String results = "";
        if(map.get("adminName").isEmpty()){
            return osc.failure("管理员姓名不能为空");
        }
        if(map.get("adminNickName").isEmpty()){
            return osc.failure("管理员登录用户名不能为空");
        }
        if(map.get("adminPhone").isEmpty()){
            return osc.failure("管理员手机号不能为空");
        }
        if(map.get("adminPassword").isEmpty()){
            return osc.failure("密码不能为空");
        }
        if(map.get("roleIds").isEmpty()){
            return osc.failure("没有选择角色");
        }
        if(map.get("adminId").isEmpty()){
            return osc.failure("adminId为空");
        }

        Boolean aBoolean = adminService.updateAdminAndRole(map);
        if(aBoolean){
            results = osc.success("修改成功");
        }else {
            results = osc.failure("修改失败");
        }
        return results;
    }

    @ResponseBody
    @RequestMapping("/deleteAdmin")
    public String deleteAdmin(@RequestBody Map<String,String> map){
        String results = "";

        if(map.get("adminId").isEmpty()){
            return osc.failure("管理员id为空，请选择一行点击删除");
        }

        Boolean aBoolean = adminService.deleteAdmin(map);
        if(aBoolean){
            results = osc.success("删除成功");
        }else {
            results = osc.failure("删除失败");
        }
        return results;
    }
}
